import { Component } from "react";
import Taro from '@tarojs/taro';
import { Input, View, Text } from '@tarojs/components';
import i18n from 'i18n-js';
import { norInject, INorInjectProps } from "@/models";
import PageContainer from "@/components/PageContainer";
import FlexScrollView from "@/components/FlexScrollView";
import { GButton } from '@/components/GButton';
import Toast from '@/utils/Toast';
import regular from '@/utils/regular';
import { observer } from 'mobx-react';
import gizwitsSdk from '@/models/gizwitsSdk';
import { checkDeviceCanControl } from '@/utils'
import { GStyleSheet, DynamicColors } from '@/utils/DarkMode';
import { DeviceDetail_Store_Key } from '@/models/deviceDetail'
import { saveDevicePassword } from '@/templates/containers/devicePasswordVerifyModal/passwordStorage';

const dstyles = GStyleSheet.create({
  content: {
    flexDirection: 'column',
    display: 'flex',
    backgroundColor: DynamicColors.cardBackgroundColor,
    padding: 15,
    paddingBottom: 30,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: DynamicColors.titleTextColor,
  },
  tip: {
    fontSize: 13,
    color: DynamicColors.subTitleTextColor,
    marginTop: 5
  },
  psdView: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  psdInput: {
    textAlign: 'center',
    borderColor: DynamicColors.borderBottomColor,
    borderWidth: 1,
    borderStyle: 'solid',
    flex: 1,
    padding: 10,
    fontSize: 16,
    marginLeft: 20,
  },
  psdTitle: {
    color: DynamicColors.normalTextColor,
  },
  bottomTip: {
    color: DynamicColors.tintColor,
    marginBottom: 30,
  },
  bottom: {
    marginTop: 20,
    marginBottom: 50,
    flexDirection: 'column',
  },
});


@norInject(DeviceDetail_Store_Key)
@observer
export default class DeviceLockPage extends Component<INorInjectProps> {

  constructor(props: any) {
    super(props);
    this.state = {
      psd: undefined,
      psdAgain: undefined,
    };
  }

  getDevice = () => {
    const { deviceDetail } = this.props;
    return deviceDetail?.device
  }

  onConfirm = async () => {
    const { psd, psdAgain } = this.state;
    if (!psd) {
      Toast.info(i18n.t('PLEASE_INPUT_PASSWORD'));
      return;
    }
    if (psd !== psdAgain) {
      Toast.info(i18n.t('PASSWORD_NOT_MATCH'));
      return;
    }
    if (psd.length !== 6 || psdAgain.length !== 6) {
      Toast.info(i18n.t('PLEASE_INPUT_PURE_NUMBER'));
      return;
    }
    const device = this.getDevice();
    if (checkDeviceCanControl({ device })) {
      Toast.loading('');
      const res = await gizwitsSdk.sendCmdLimit({ device, data: { password: parseInt(psd, 10), password_power: true } });
      Toast.hideLoading();
      if (res.success) {
        saveDevicePassword({ device, password: psd });
        Toast.success(i18n.t('PASSWORD_SET_SUCCESS'));
        setTimeout(() => {
          Taro.navigateBack();
        }, 300);
      } else {
        Toast.info(i18n.t('PASSWORD_SET_FAIL'));
      }
    }
  }

  onTipsPress = async () => {
    const device = this.getDevice();
    if (checkDeviceCanControl({ device })) {
      Toast.loading('');
      const res = await gizwitsSdk.sendCmdLimit({ device, data: { password: false, password_power: 0 } });
      Toast.hideLoading();
      if (res.success) {
        Toast.success(i18n.t('PASSWORD_CLEAR_SUCCESS'));
        setTimeout(() => {
          Taro.navigateBack();
        }, 300);
      } else {
        Toast.info(i18n.t('PASSWORD_CLEAR_FAIL'));
      }
    }
  }

  renderTextInput = ({ title, value, onChangeText }) => {
    const styles = dstyles.style;
    return (<View style={styles.psdView}>
      <Text style={styles.psdTitle}>{title}</Text>
      <Input
        maxlength={6}
        type='number'
        style={styles.psdInput}
        value={value}
        onInput={onChangeText}
        placeholder={i18n.t('PLEASE_INPUT_PASSWORD')}
      />
    </View>)
  }

  changePsd = ({ value, key }) => {
    if (value && value.length > 0) {
      if (regular.number.test(value)) {
        this.setState({ [key]: value });
      }
    } else {
      this.setState({ [key]: value });
    }
  }

  render() {
    const styles = dstyles.style;
    const { psd, psdAgain } = this.state;

    return (
      <PageContainer title={i18n.t('LOCK')}>
        <View style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          <FlexScrollView id='deviceLickList'>
            <View style={styles.content}>
              <Text style={styles.title}>{i18n.t('SET_PASSWORD')}</Text>
              <Text style={styles.tip}>{i18n.t('LOCK_TIP')}</Text>
              <View>
                {this.renderTextInput({ title: i18n.t('INPUT_PSD'), value: psd, onChangeText: (e) => { this.changePsd({ value: e.detail.value, key: 'psd' }) } })}
                {this.renderTextInput({ title: i18n.t('INPUT_AGAIN'), value: psdAgain, onChangeText: (e) => { this.changePsd({ value: e.detail.value, key: 'psdAgain' }) } })}
              </View>
            </View>
          </FlexScrollView>
          <View style={styles.bottom} className='centerFlex'>
            <Text style={styles.bottomTip} onClick={this.onTipsPress}>{i18n.t('CLEAR_PASSWORD')}</Text>
            <GButton text={i18n.t('SAVE')} onPress={this.onConfirm} />
          </View>
        </View>
      </PageContainer >
    );
  }
}
